var express = require('express');
var city = require('./city');
var data1 = require('./date');
var data2 = require('./json1');
var app = new express();


app.get('/api/city', function (req, res) {
    res.setHeader('Content-Type', 'text/plain;charset=utf8');
    res.end(JSON.stringify({
        code: 200,
        data: city
    }))
    return
})

let page_size = 5;
let page_num = 5;
let total = 30;
app.post('/api/list', function (req, res) {
    res.setHeader('Content-Type', 'text/plain;charset=utf8');
    let str = '';
    req.on('data', chunk => {
        str += chunk;
    });
    req.on('end', () => {
        let data = {
            code: 400
        }
        if (str.length) {
            str = JSON.parse(str) || {};
            switch (Number(str.type)) {
                case 0:
                    if (!str.centerId) {
                        data.tip = 'id不能为空'
                    }
                    if (!str.time) {
                        data.tip = '时间不能为空'
                    } else {
                        data.tip = '成功'
                        data.code = 200;
                        data.total = total;
                        data.data = getData(0, str)
                        console.log('data: ', data);
                    }
                    break;
                case 1:
                    if (!str.centerId) {
                        data.tip = 'id不能为空'
                    }
                    if (!str.startTime) {
                        data.tip = '起始时间不能为空'
                    } 
                    if (!str.endTime) {
                        data.tip = '结束时间不能为空'
                    } else {
                        data.tip = '成功'
                        data.code = 200;
                        data.total = total;
                        data.data = getData(1, str)
                        console.log('data: ', data);
                    }
            }
            res.end(JSON.stringify(data))
            return
        } else {
            data.tip = 'id不能为空'
            res.end(JSON.stringify(data))
            return
        }
    })
})


function getData (type, str) {
    page_size = str.page_size || 5;
    page_num = str.page_num ? str.page_num -1 : 0;
    return type == 1 ? data2.slice(page_num, page_num + page_size) : data1
}

app.post('/api/det', function (req,res){
    let id = parseInt(req.query.id);
    let data = {
        code: 400
    }
    if (!id) {
        data.tip = '结束时间不能为空'
    } else {
        data.tip = '删除成功'
    }
    res.end(JSON.stringify(data))
    return
})



var server = app.listen(3000, 'localhost', function (req, res, next) {
    var host = server.address().address
    var port = server.address().port
    console.log("http://%s:%s", host, port)
})